import { defineComponent, ref, reactive, onMounted, watch } from 'vue';
import SearchBar from './components/searchBar/index';
import TaskList from './components/taskList/index';
import HistoryList from './components/historyList/index';
import { ElMessage } from 'element-plus/lib/index';
import { downLoadFile } from '@/utils/http';
import './index.scss';
import API from '@/services';
import PageCaontainer from '@/arco-components/PageContainer';
const SystemSetting = defineComponent({
  name: 'GetNumberTask',
  components: { SearchBar, TaskList, HistoryList },
  props: {},
  setup: (props, { slots, attrs, emit }) => {
    // apis
    const {
      taskManagerV1: {
        postExecTask,
        postTaskList,
        postTaskHis,
        postDelTask,
        postDelTaskHis,
        getHisLog
      },
    } = API;

    // 日志
    const logDisabled: any = ref(false);
    const logInfo: any = ref('');

    const tabActive = ref('task');
    const changeActive = (val = 'task') => {
      // 情况选中keys
      rowsKeys.value = [];
      queryParams.cycleType = 0;
      queryParams.order = 1;
      queryParams.sortBy = '';
      queryParams.startDate = '';
      queryParams.endDate = '';
      queryParams.keyword = '';
      queryParams.pageNum = 1;
      queryParams.status = '';
      queryParams.pageSize = 10;
      tabActive.value = val;
    };
    // 查询条件
    const queryParams = reactive({
      cycleType: 0,
      order: 1,
      sortBy: '',
      startDate: '',
      endDate: '',
      keyword: '',
      pageNum: 1,
      status: '',
      pageSize: 10
    });
    const taskData = reactive({
      pageData: {}
    });
    const historyData = reactive({
      pageData: {}
    });
    // 选中tablekeys
    const rowsKeys: any = ref([]);

    // loading
    const loading = ref(false);

    // watch
    watch([queryParams, tabActive], () => {
      getTableList();
    });

    // 加载完成
    onMounted(() => {
      getTableList();
    });

    // 获取table数据
    const getTableList = async () => {
      const query = {
        pageNum: queryParams.pageNum,
        pageSize: queryParams.pageSize
      } as any;

      if (queryParams.cycleType) {
        query['cycleType'] = queryParams.cycleType;
      }
      if (queryParams.startDate) {
        query['startDate'] = queryParams.startDate;
      }
      if (queryParams.endDate) {
        query['endDate'] = queryParams.endDate;
      }
      if (queryParams.keyword) {
        query['keyword'] = queryParams.keyword;
      }
      // 只有历史有状态
      if (queryParams.status && tabActive.value === 'history') {
        query['status'] = queryParams.status;
      }
      if (queryParams.sortBy) {
        query['order'] = queryParams.order;
        query['sortBy'] = queryParams.sortBy;
      }
      loading.value = true;
      let data, code;
      if (tabActive.value === 'task') {
        ({ data, code } = await postTaskList(query));
        if (code === 200) {
          taskData.pageData = data as any;
        }
      } else {
        ({ data, code } = await postTaskHis(query));
        if (code === 200) {
          historyData.pageData = data as any;
        }
      }

      loading.value = false;
    };
    //分页查询
    const pageChange = (v: any) => {
      queryParams.pageNum = 1;
      queryParams.pageSize = v;
      getTableList();
    };
    //页数改变
    const currentChange = (v: any) => {
      queryParams.pageNum = v;
      getTableList();
    };
    //查询条件
    const onDoSearch = (query: any) => {
      queryParams.keyword = query.keyWords;
      if (query.createDate) {
        queryParams.startDate = query.createDate[0];
        queryParams.endDate = query.createDate[1];
      } else {
        queryParams.startDate = "";
        queryParams.endDate = "";
      }
      queryParams.status = query.status;
      queryParams.cycleType = query.cycleType;
    };
    // 排序
    const sortTable = (sort: any) => {
      if (sort.prop) {
        queryParams.order = sort.order === 'ascending' ? 1 : 2;
        queryParams.sortBy = sort.prop;
      } else {
        queryParams.order = 1;
        queryParams.sortBy = '';
      }
    };

    // 选中keys
    const selectKeys = (keys: any) => {
      rowsKeys.value = keys;
    };

    // 执行
    const doExecTask = async () => {
      if (rowsKeys.value.length === 0) {
        ElMessage.error('未选中任务');
        return;
      }
      try {
        const { code } = await postExecTask({ taskIds: rowsKeys.value });
        if (code === 200) {
          ElMessage.success('执行成功');
          getTableList();
          rowsKeys.value = [];
        }
      } catch (error) {
        ElMessage.error('执行失败');
      }
    };

    // 删除
    const doDeleteTask = async () => {
      if (rowsKeys.value.length === 0) {
        ElMessage.error('未选中任务');
        return;
      }
      try {
        let state = null;
        if (tabActive.value === 'task') {
          const { code } = await postDelTask({ taskIds: rowsKeys.value });
          state = code;
        } else {
          const { code } = await postDelTaskHis({ taskIds: rowsKeys.value });
          state = code;
        }

        if (state === 200) {
          ElMessage.success('删除成功');
          getTableList();
          rowsKeys.value = [];
        }
      } catch (error) {
        ElMessage.error('删除失败');
      }
    };
    // table操作列表-执行
    const tableOptionExecTask = (taskId: any) => {
      rowsKeys.value = [taskId];
      doExecTask();
    };
    // 日志
    const getHisLogs = async (taskId: any) => {
      try {
        const { code, data } = await getHisLog({ taskHisId: taskId });
        if (code === 200) {
          logInfo.value = data;
          logDisabled.value = true;
        }
      } catch (error) {
        ElMessage.error('获取日志失败');
      }
    };

    // 下载
    const downloadHistory = async () => {
      if (rowsKeys.value.length === 0) {
        ElMessage.error('未选中任务');
        return;
      }
      const urlParams = rowsKeys.value
        .map((item: any) => {
          return `hisIds=${item}`;
        })
        .join('&');
      downLoadFile({
        url: '/task-manager/task-his/data/download?' + urlParams,
        method: 'get'
      });
    };

    return () => {
      return (
        <PageCaontainer>
        <div class="getnum-task-mgmt-wrap" v-loading={loading.value}>
          <div class="search-wrap">
            <search-bar
              currentTab={tabActive.value}
              onChangeActive={changeActive}
              search={onDoSearch}
            />
          </div>
          <div class="list-wrap">
            <div class="operator-btn-wrap">
              <el-button onClick={doExecTask}>
                执行
              </el-button>
              {tabActive.value === 'history' && (
                <el-button onClick={downloadHistory}>
                  下载
                </el-button>
              )}
              <el-button onClick={doDeleteTask}>
                删除
              </el-button>
            </div>
            <div class="table-wrap">
              {tabActive.value === 'task' ? (
                <TaskList
                  pageData={taskData.pageData}
                  onSelectKeys={selectKeys}
                  onPageSizeChange={pageChange}
                  onCurrentChange={currentChange}
                  onSortTable={sortTable}
                />
              ) : (
                <history-list
                  pageData={historyData.pageData}
                  onLogInfo={getHisLogs}
                  onSortTable={sortTable}
                  onExecTask={tableOptionExecTask}
                  onSelectKeys={selectKeys}
                  onPageSizeChange={pageChange}
                  onCurrentChange={currentChange}
                />
              )}
            </div>
          </div>
          <el-dialog
            v-model={logDisabled.value}
            custom-class="taskLogDialog"
            title="任务日志"
            width="570px"
            onBeforeClose={() => {
              logDisabled.value = false;
            }}
          >
            <span>{logInfo.value}</span>
          </el-dialog>
        </div>
        </PageCaontainer>
      );
    };
  }
});

export default SystemSetting;
